package com.blensmile.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.support.annotation.StringRes;
import android.util.AttributeSet;
import android.view.View;

import com.blensmile.R;
import com.blensmile.utils.DensityUtils;

import java.util.ArrayList;

/**
 * Created by Blensmile on 2016/12/1.
 */
public class DrawPolygon extends View{

    private static int IMG_DEF_WIDTH = 30;
    private int width = 0;
    private int maxRadius = 0;
    private int[] grades = new int[]{1,2,3,4,0};
    private ArrayList<Point[]> pointList = new ArrayList<>();

    private @DrawableRes int Drawable[] = {R.drawable.mothertong,
            R.drawable.expression,
            R.drawable.comprehensive,
            R.drawable.application,
            R.drawable.logical};
    private @StringRes int strings[] = {R.string.native_think,
            R.string.language_expression,
            R.string.sentence_comprehension,
            R.string.comprehensive,
            R.string.language_logic};

    //自定义的参数
    private @ColorInt int LineColor;//五边形线条的颜色
    private @ColorInt int MarkColor;//成绩区域的颜色
    private @ColorInt int TextColor;//文字的颜色
    private int ImageWidth;//图标的宽度
    private int TextSize;//文字大小

    private int radarMargin = DensityUtils.dip2px(getContext(), 4);//雷达图与标题的间距
    private Paint linePaint;
    private Paint markPaint;
    private Paint textPaint;

    public DrawPolygon(Context context) {
        this(context,null);
    }

    public DrawPolygon(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public DrawPolygon(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RadarStyle);
        LineColor = a.getColor(R.styleable.RadarStyle_LineColor,Color.WHITE);
        MarkColor = a.getColor(R.styleable.RadarStyle_PathColor,Color.parseColor("#5ebb5e"));
        TextColor = a.getColor(R.styleable.RadarStyle_TextColor,Color.WHITE);
        ImageWidth = a.getDimensionPixelSize(R.styleable.RadarStyle_ImgWidth,DensityUtils.dip2px(context,IMG_DEF_WIDTH));
        TextSize = a.getDimensionPixelSize(R.styleable.RadarStyle_TextSize,DensityUtils.dip2px(context,12));
        a.recycle();
        initPaint();
    }

    /**
     * 初始化画笔
     */
    private void initPaint() {
        linePaint = new Paint();
        linePaint.setAntiAlias(true);
        linePaint.setStrokeWidth(DensityUtils.dip2px(getContext(),1));
        linePaint.setColor(LineColor);
        linePaint.setStyle(Paint.Style.STROKE);

        markPaint = new Paint();
        markPaint.setAntiAlias(true);
        markPaint.setColor(MarkColor);
        markPaint.setAlpha(100);
        markPaint.setStrokeWidth(3);
        markPaint.setStyle(Paint.Style.FILL_AND_STROKE);

        textPaint = new Paint();
        textPaint.setAntiAlias(true);
        textPaint.setTextSize(TextSize);
        textPaint.setColor(TextColor);
        textPaint.setStyle(Paint.Style.FILL);
    }

    /**
     * 初始化五边形的点
     */
    private void initPoints(){
        if (!isInEditMode()) {
            setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }
        maxRadius = width / 3;
        pointList.clear();
        for (int i = 0; i < 5; i++) {
            int r = maxRadius * (1+i) / 5;
            pointList.add(getPoints( r));
        }
    }

    /** 设置成绩
     *
     * @param grades
     */
    public void setGrades(int[] grades) {
        if(grades.length<4){
            return;
        }
        this.grades = grades;
        invalidate();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int wsize = MeasureSpec.getSize(widthMeasureSpec);
        width = wsize;
        setMeasuredDimension(width,width);
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas) {
        initPoints();
        drawResult(canvas);
    }

    /** 绘制
     *
     * @param canvas
     */
    private void drawResult(Canvas canvas) {
        for (int i = 0; i < 5; i++) {
            Path path = new Path();
            Point[] points = pointList.get(i);
            path.moveTo(points[4].x,points[4].y);
            for (int j = 0; j < 5; j++) {
                path.lineTo(points[j].x, points[j].y);
            }
            path.close();
            canvas.drawPath(path, linePaint);
        }
        int itemWidth = ImageWidth;
        int polyPadding = DensityUtils.dip2px(getContext(), 10);
        Point[] points = pointList.get(4);
        for (int i = 0; i < 5; i++) {
            String str = getContext().getString(strings[i]);
            int textWidth =(int) textPaint.measureText(str);
            itemWidth = itemWidth>textWidth?itemWidth:textWidth;
            int itemHeight = ImageWidth + TextSize + radarMargin;
            int x,y;
            switch (i) {
                case 0:
                    x = points[i].x - itemWidth/2;
                    y = points[i].y - itemHeight - polyPadding;
                    drawIcon(Drawable[0],ImageWidth<itemWidth?(x+(itemWidth-ImageWidth)/2):x,y,canvas);
                    canvas.drawText(str,textWidth<itemWidth?(x+(itemWidth-textWidth)/2):x,points[i].y-polyPadding,textPaint);
                    break;
                case 1:
                    x = points[i].x - itemWidth - polyPadding;
                    y = points[i].y - itemHeight/2;
                    drawIcon(Drawable[1],ImageWidth<itemWidth?(x+(itemWidth-ImageWidth)/2):x,y,canvas);
                    canvas.drawText(str,textWidth<itemWidth?(x+(itemWidth-textWidth)/2):x,y+itemHeight,textPaint);
                    break;
                case 2:
                    x = points[i].x - itemWidth - polyPadding;
                    y = points[i].y;
                    drawIcon(Drawable[2],ImageWidth<itemWidth?(x+(itemWidth-ImageWidth)/2):x,y,canvas);
                    canvas.drawText(str,textWidth<itemWidth?(x+(itemWidth-textWidth)/2):x,y+itemHeight,textPaint);
                    break;
                case 3:
                    x = points[i].x + polyPadding;
                    y = points[i].y;
                    drawIcon(Drawable[3],ImageWidth<itemWidth?(x+(itemWidth-ImageWidth)/2):x,y,canvas);
                    canvas.drawText(str,textWidth<itemWidth?(x+(itemWidth-textWidth)/2):x,y+itemHeight,textPaint);
                    break;
                case 4:
                    x = points[i].x + polyPadding;
                    y = points[i].y - itemHeight/2;
                    drawIcon(Drawable[4],ImageWidth<itemWidth?(x+(itemWidth-ImageWidth)/2):x,y,canvas);
                    canvas.drawText(str,textWidth<itemWidth?(x+(itemWidth-textWidth)/2):x,y+itemHeight,textPaint);
                    break;
            }
        }

        Path path2 = new Path();
        int sum = 0;
        for (int i = 0; i < grades.length; i++) {
            sum += grades[i];
            if (grades[i] > 4) {
                grades[i] = 4;
            }
            Point point  = getPoint((1+grades[i])*maxRadius/5,i);
            if(i==0){
                Point point1  = getPoint((1+grades[4])*maxRadius/5,4);
                path2.moveTo(point1.x, point1.y);
            }
            path2.lineTo(point.x,point.y);
        }
        if (sum > 0) {
            canvas.drawPath(path2, markPaint);
        }
        path2.close();
    }

    /** 画图标
     *
     * @param icon
     * @param x
     * @param y
     * @param canvas
     */
    private void drawIcon(@DrawableRes int icon, int x, int y,Canvas canvas){
        try {
            Drawable drawable = getContext().getResources().getDrawable(icon);
            drawable.setBounds(x,y,x+ImageWidth,y+ImageWidth);
            drawable.draw(canvas);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /** 获取一组五边形坐标
     *
     * @param r
     * @return
     */
    private Point[] getPoints( int r){
        Point[] points = new Point[5];
        for (int i = 0; i < 5; i++) {
           points[i] = getPoint(r,i);
        }
        return points;
    }

    /** 获取一个五边形坐标
     *
     * @param r
     * @param i
     * @return
     */
    private Point getPoint(int r,int i){
        int startx = width / 2;
        int starty = (width / 2) - r+(int)(maxRadius - maxRadius* Math.cos((Math.PI)/6));
        Point point = new Point();
        point.x = (int) (startx - r * Math.sin(((2 * Math.PI) / 5) * i));
        point.y = (int) (starty + r - r * Math.cos(((2 * Math.PI) / 5) * i));
        return point;
    }

}